package com.zzk.audiovideodemo.textureView

import android.graphics.SurfaceTexture
import android.hardware.Camera
import android.os.Bundle
import android.view.TextureView
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.LogUtils
import com.zzk.audiovideodemo.R
import kotlinx.android.synthetic.main.activity_textureview_camera1.*

/**
 * TextureView使用示例，使用Camera1
 *
 * @author king
 * @time 2020-3-17 14:48
 */
class TextureViewCamera1Activity : AppCompatActivity(), TextureView.SurfaceTextureListener {

    private var camera: Camera? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_textureview_camera1)
        tv_video.surfaceTextureListener = this
    }

    override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
        LogUtils.i("TextureViewCameraActivity->onSurfaceTextureAvailable")
        //在SurfaceTexture准备使用时调用,回调中拿到SurfaceTexture，并把他设置给camera，作为承载、预览数据流的载体
        camera = Camera.open()
        try {
            camera?.setPreviewTexture(tv_video.surfaceTexture)
            camera?.setDisplayOrientation(90)
            camera?.startPreview()
        } catch (e: Exception) {

        }
    }

    override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
        LogUtils.i("TextureViewCameraActivity->onSurfaceTextureSizeChanged")
        //当SurfaceTexture缓冲区大小更改时调用
    }

    override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
        LogUtils.i("TextureViewCameraActivity->onSurfaceTextureUpdated")
        //当SurfaceTexture有更新时调用
    }

    override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
        LogUtils.i("TextureViewCameraActivity->onSurfaceTextureDestroyed")
        //当指定SurfaceTexture即将被销毁时调用。关闭预览，释放camera资源
        //如果返回true，则调用此方法后，表面纹理中不会发生渲染。
        //如果返回false，则客户端需要调用release()。大多数应用程序应该返回true
        camera?.stopPreview()
        camera?.release()
        return true
    }

}
